<?php


$status = Mage::getSingleton('importplus/status');
//$_attributeCode = 'diamond_size';
$_attributeCode = $status->getAttributeCode();

$eavAttributeModel = Mage::getModel('eav/entity_attribute');
$attribute_id = $eavAttributeModel->getIdByCode('catalog_product',$_attributeCode);
$target = false;


$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php         
        foreach($_attributes as $_attribute): 
        if($attribute_id && $_attribute->getAttributeId() == $attribute_id) {
            $target = true;
        }
    ?>
        <dt><label><?php echo $_attribute->getLabel() ?><span class="required">&nbsp;*</span></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
          <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select" optitle="<?php echo strtolower($_attribute->getLabel()); ?>">
            <option><?php if($target) {echo $this->__('-- Choose Carat Weight --');} else {$this->__('Choose an Option...');} ?></option>
          </select>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
         <?php if ($target) { ?>
            
            if (typeof ConfigProduct== 'undefined') {
                var ConfigProduct= {};
            }

            ConfigProduct.Config = Class.create();
            ConfigProduct.Config.prototype = {
                initialize: function(config){
                    this.config     = config;
                    this.taxConfig  = this.config.taxConfig;
                    if (config.containerId) {
                        this.settings   = $$('#' + config.containerId + ' ' + '.super-attribute-select');
                    } else {
                        this.settings   = $$('.super-attribute-select');
                    }
                    this.state      = new Hash();
                    this.priceTemplate = new Template(this.config.template);
                    this.prices     = config.prices;
                    
                    // Set default values from config
                    if (config.defaultValues) {
                        this.values = config.defaultValues;
                    }
                    
                    // Overwrite defaults by url
                    var separatorIndex = window.location.href.indexOf('#');
                    if (separatorIndex != -1) {
                        var paramsStr = window.location.href.substr(separatorIndex+1);
                        var urlValues = paramsStr.toQueryParams();
                        if (!this.values) {
                            this.values = {};
                        }
                        for (var i in urlValues) {
                            this.values[i] = urlValues[i];
                        }
                    }
                    
                    // Overwrite defaults by inputs values if needed
                    if (config.inputsInitialized) {
                        this.values = {};
                        this.settings.each(function(element) {
                            if (element.value) {
                                var attributeId = element.id.replace(/[a-z]*/, '');
                                this.values[attributeId] = element.value;
                            }
                        }.bind(this));
                    }
                        
                    // Put events to check select reloads 
                    this.settings.each(function(element){
                        Event.observe(element, 'change', this.configure.bind(this))
                    }.bind(this));

                    // fill state
                    this.settings.each(function(element){
                        var attributeId = element.id.replace(/[a-z]*/, '');
                        if(attributeId && this.config.attributes[attributeId]) {
                            element.config = this.config.attributes[attributeId];
                            element.attributeId = attributeId;
                            this.state[attributeId] = false;
                        }
                    }.bind(this))

                    // Init settings dropdown
                    var childSettings = [];
                    for(var i=this.settings.length-1;i>=0;i--){
                        var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
                        var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
                        if (i == 0){
                            this.fillSelect(this.settings[i])
                        } else {
                            this.settings[i].disabled = true;
                        }
                        $(this.settings[i]).childSettings = childSettings.clone();
                        $(this.settings[i]).prevSetting   = prevSetting;
                        $(this.settings[i]).nextSetting   = nextSetting;
                        childSettings.push(this.settings[i]);
                    }

                    // Set values to inputs
                    this.configureForValues();
                    document.observe("dom:loaded", this.configureForValues.bind(this));
                },
                
                configureForValues: function () {
                    if (this.values) {
                        this.settings.each(function(element){
                            var attributeId = element.attributeId;
                            element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
                            this.configureElement(element);
                        }.bind(this));
                    }
                },

                configure: function(event){
                    var element = Event.element(event);
                    this.configureElement(element);
                },

                configureElement : function(element) {
                    this.reloadOptionLabels(element);
                    if(element.value){
                        this.state[element.config.id] = element.value;
                        if(element.nextSetting){
                            element.nextSetting.disabled = false;
                            this.fillSelect(element.nextSetting);
                            this.resetChildren(element.nextSetting);
                        }
                    }
                    else {
                        this.resetChildren(element);
                    }
                    this.reloadPrice();
                },

                reloadOptionLabels: function(element){
                    var selectedPrice;
                    if(element.options[element.selectedIndex].config && !this.config.stablePrices){
                        selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
                    }
                    else{
                        selectedPrice = 0;
                    }
                    for(var i=0;i<element.options.length;i++){
                        if(element.options[i].config){
                            element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
                        }
                    }
                },

                resetChildren : function(element){
                    if(element.childSettings) {
                        for(var i=0;i<element.childSettings.length;i++){
                            element.childSettings[i].selectedIndex = 0;
                            element.childSettings[i].disabled = true;
                            if(element.config){
                                this.state[element.config.id] = false;
                            }
                        }
                    }
                },

                fillSelect: function(element){
                    var attributeId = element.id.replace(/[a-z]*/, '');
                    var options = this.getAttributeOptions(attributeId);

                    this.clearSelect(element);
                    element.options[0] = new Option(this.config.chooseText, '');

                    var prevConfig = false;
                    if(element.prevSetting){
                        prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
                    }
                    
                    if(options) {
                        var index = 1;
                        for(var i=0;i<options.length;i++){
                            var allowedProducts = [];
                            if(prevConfig) {
                                for(var j=0;j<options[i].products.length;j++){
                                    if(prevConfig.config.allowedProducts
                                        && prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
                                        allowedProducts.push(options[i].products[j]);
                                    }
                                }
                            } else {
                                allowedProducts = options[i].products.clone();
                            }

                            if(allowedProducts.size()>0){
                                options[i].allowedProducts = allowedProducts;
                                element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
                                if (typeof options[i].price != 'undefined') {
                                    element.options[index].setAttribute('price', options[i].price);
                                }
                                element.options[index].config = options[i];
                                index++;
                            }
                        }
                    }
                },

                getOptionLabel: function(option, price){
                    var price = parseFloat(price);
                    if (this.taxConfig.includeTax) {
                        var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
                        var excl = price - tax;
                        var incl = excl*(1+(this.taxConfig.currentTax/100));
                    } else {
                        var tax = price * (this.taxConfig.currentTax / 100);
                        var excl = price;
                        var incl = excl + tax;
                    }

                    if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
                        price = incl;
                    } else {
                        price = excl;
                    }

                    var str = option.label;
                    if(price){
                        if (this.taxConfig.showBothPrices) {
                            str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
                        } else {
                            str+= ' ' + this.formatPrice(price, true);
                        }
                    }
                    return str;
                },

                formatPrice: function(price, showSign){
                    var str = '';
                    price = parseFloat(price);
                    if(showSign){
                        if(price<0){
                            str+= '-';
                            price = -price;
                        }
                        else{
                            str+= '+';
                        }
                    }

                    var roundedPrice = (Math.round(price*100)/100).toString();

                    if (this.prices && this.prices[roundedPrice]) {
                        str+= this.prices[roundedPrice];
                    }
                    else {
                        str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
                    }
                    return str;
                },

                clearSelect: function(element){
                    for(var i=element.options.length-1;i>=0;i--){
                        element.remove(i);
                    }
                },

                getAttributeOptions: function(attributeId){
                    if(this.config.attributes[attributeId]){
                        return this.config.attributes[attributeId].options;
                    }
                },

                reloadPrice: function(){
                    $$('.product_c_options').each(function(element){
                        element.hide();
                    });

                    $$('.product-custom-option').each(function(element){
                        var optionId = 0;
                        element.name.sub(/[0-9]+/, function(match){
                            optionId = match[0];
                        });
                        if (element.type == 'checkbox' || element.type == 'radio') {
                            if (element.checked) {
                                element.checked =false;
                            }
                        } else if(element.type == 'select-one' || element.type == 'select-multiple') {
                            if (element.options) {
                                $A(element.options).each(function(selectOption){
                                    if (selectOption.selected) {
                                       selectOption.selected =false;
                                    }
                                });
                            }
                        }
                    });
                    try {
                        optionsPrice.changePrice('options',0);
                        optionsPrice.changePrice('optionsPriceInclTax', 0);
                        optionsPrice.reload();
                    } catch (e) {

                }
            
                    if (this.config.disablePriceReload) {
                        return;
                    }
                    
                    var price    = 0;
                    var oldPrice = 0;
                    for(var i=this.settings.length-1;i>=0;i--){
                        var selected = this.settings[i].options[this.settings[i].selectedIndex];
                        if(selected.config){
                            var productId = selected.config.products[0]; ;//options[element.selectedIndex].products[0];
                            if ($('product_'+productId)){
                                $('product_'+productId).show(); 
                                var tags = $$('.product_'+productId);
                                var taglength = tags.length;
                                for( var ix = 0; ix < tags.length; ix ++) {
                                    tags[ix].show(); 
                                }
                            }
                            $$('input[name="product"]')[0].value = productId;
                            var action = $('product_addtocart_form').getAttribute('action');
                            action = action.substr(0,action.length - 1);
                            var pos = action.lastIndexOf("/");
                            var action = action.substr(0,pos) + '/'+productId+'/';
                            $('product_addtocart_form').setAttribute('action', action);
                             
                            price    += parseFloat(selected.config.price);
                            oldPrice += parseFloat(selected.config.oldPrice);
                        }
                    }

                    optionsPrice.changePrice('config', {'price': price, 'oldPrice': oldPrice});
                    optionsPrice.reload();

                    return price;

                    if($('product-price-'+this.config.productId)){
                        $('product-price-'+this.config.productId).innerHTML = price;
                    }
                    this.reloadOldPrice();
                },

                reloadOldPrice: function(){
                    if (this.config.disablePriceReload) {
                        return;
                    }
                    if ($('old-price-'+this.config.productId)) {

                        var price = parseFloat(this.config.oldPrice);
                        for(var i=this.settings.length-1;i>=0;i--){
                            var selected = this.settings[i].options[this.settings[i].selectedIndex];
                            if(selected.config){
                                price+= parseFloat(selected.config.price);
                            }
                        }
                        if (price < 0)
                            price = 0;
                        price = this.formatPrice(price);

                        if($('old-price-'+this.config.productId)){
                            $('old-price-'+this.config.productId).innerHTML = price;
                        }

                    }
                }
            }
            var spConfig = new ConfigProduct.Config(<?php echo $this->getDiamondJsonConfig();?>);
         <?php } else  { ?>
             var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
        <?php } ?>
    </script>
<?php
    endif;
    if ($target) :
?>
<?php if((Mage::getSingleton('customer/session')->isLoggedIn())): ?> 
    <script type="text/javascript">
    //<![CDATA[
    function getPriceToAdd(optionvalue, oldprice) {
        var value = parseFloat(optionvalue['pricing_value']);
        if (optionvalue['is_percentage']) {
            return Math.round(value*oldprice)/100;
        } else {
            return value;
        }
    }
<?php else: ?>

  <script type="text/javascript">
    //<![CDATA[
    function getPriceToAdd(optionvalue, oldprice) {
        var value = parseFloat(optionvalue['pricing_value']);
        if (optionvalue['is_percentage']) {
            return Math.round(value*oldprice)/100;
        } else {
            return value;
        }
    }
<?php endif; ?>
    var optionTextCounter = {
        count : function(field,cntfield,maxlimit){
            if (field.value.length > maxlimit){
                field.value = field.value.substring(0, maxlimit);
            } else {
                cntfield.innerHTML = maxlimit - field.value.length;
            }
        }
    }

    Product.Options = Class.create();
    Product.Options.prototype = {
        initialize : function(config){
            this.config = config;
            this.reloadPrice();
            document.observe("dom:loaded", this.reloadPrice.bind(this));
        },
        reloadPrice : function(){
            price = new Number();
            config = this.config;
            skipIds = [];
            $$('.product-custom-option').each(function(element){
                var optionId = 0;
                element.name.sub(/[0-9]+/, function(match){
                    optionId = match[0];
                });
                if (this.config[optionId]) {
                    if (element.type == 'checkbox' || element.type == 'radio') {
                        if (element.checked) {
                            if (config[optionId][element.getValue()]) {
                               // price += parseFloat(config[optionId][element.getValue()]);
                                price += getPriceToAdd(config[optionId][element.getValue()], price);
                            }
                        }
                    } else if(element.hasClassName('datetime-picker') && !skipIds.include(optionId)) {
                        dateSelected = true;
                        $$('.product-custom-option[id^="options_' + optionId + '"]').each(function(dt){
                            if (dt.getValue() == '') {
                                dateSelected = false;
                            }
                        });
                        if (dateSelected) {
                            //price += parseFloat(this.config[optionId]);
                             price += getPriceToAdd(this.config[optionId], price);
                            skipIds[optionId] = optionId;
                        }
                    } else if(element.type == 'select-one' || element.type == 'select-multiple') {
                        if (element.options) {
                            $A(element.options).each(function(selectOption){
                                if (selectOption.selected) {
                                    if (this.config[optionId][selectOption.value]) {
                                        //price += parseFloat(this.config[optionId][selectOption.value]);
                                        price += getPriceToAdd(this.config[optionId][selectOption.value], price);
                                    }
                                }
                            });
                        }
                    } else {
                        if (element.getValue().strip() != '') {
                            //price += parseFloat(this.config[optionId]);
                            price += getPriceToAdd(this.config[optionId], price);
                        }
                    }
                }
            });
            try {
                optionsPrice.changePrice('options', price);
                optionsPrice.changePrice('optionsPriceInclTax', price);
                optionsPrice.reload();
            } catch (e) {

            }
        }
    }
    function validateOptionsCallback(elmId, result){
        var container = $(elmId).up('ul.options-list');
        if (result == 'failed') {
            container.removeClassName('validation-passed');
            container.addClassName('validation-failed');
        } else {
            container.removeClassName('validation-failed');
            container.addClassName('validation-passed');
        }
    }
    var opConfig = new Product.Options(<?php echo $this->getAttributeJsonConfig() ?>);
    //]]>
    </script>
    
<?php
        echo $this->getProductsOptions();
        echo '<script>Event.observe(window, "load", function() {
        $$(".product_c_options").each(function(element){element.hide();});
    }); 
</script>';
    endif;

